import requests
import aiohttp
import logging

from api.xbot.xbot_base_api import XbotBaseApi


class LoginApi(XbotBaseApi):

    # ==================== Login 登录模块 ====================
    def login_auto_heart_beat_log(self, wxid: str):
        """自动心跳日志"""
        params = {"wxid": wxid}
        
        # 构造API URL，确保包含/api路径
        api_url = f"{self.base_url}/Login/AutoHeartBeatLog"
        if '/api/' not in api_url and not api_url.endswith('/api'):
            base_part = api_url.split('/Login/AutoHeartBeatLog')[0]
            api_url = f"{base_part}/api/Login/AutoHeartBeatLog"
            
        return requests.post(
            api_url,
            params=params
        ).json()

    def login_auto_heart_beat(self, wxid: str):
        """开启自动心跳/自动二次登录"""
        params = {"wxid": wxid}
        
        # 构造API URL，确保包含/api路径
        api_url = f"{self.base_url}/Login/AutoHeartBeat"
        if '/api/' not in api_url and not api_url.endswith('/api'):
            base_part = api_url.split('/Login/AutoHeartBeat')[0]
            api_url = f"{base_part}/api/Login/AutoHeartBeat"
            
        return requests.post(
            api_url,
            params=params
        ).json()

    def login_close_auto_heart_beat(self, wxid: str):
        """关闭自动心跳/二次登录"""
        params = {"wxid": wxid}
        
        # 构造API URL，确保包含/api路径
        api_url = f"{self.base_url}/Login/CloseAutoHeartBeat"
        if '/api/' not in api_url and not api_url.endswith('/api'):
            base_part = api_url.split('/Login/CloseAutoHeartBeat')[0]
            api_url = f"{base_part}/api/Login/CloseAutoHeartBeat"
            
        return requests.post(
            api_url,
            params=params
        ).json()

    def login_get_qr_x(self, device_type: str = "my Pad", device_id: str = None, device_name: str = "my Pad", proxy: dict = None):
        """获取二维码(安卓Pad-绕过验证码)"""
        logger = logging.getLogger("log")
        
        body = {
            "DeviceID": device_id or f"device-{device_type}",
            "DeviceName": device_name or device_type,
            "LoginType": device_type,
            "Proxy": proxy or {}
        }
        
        # 构造API URL，确保包含/api路径
        api_url = f"{self.base_url}/Login/LoginGetQRx"
        if '/api/' not in api_url and not api_url.endswith('/api'):
            # 如果URL中不包含/api/，则在URL和路径之间添加/api
            base_part = api_url.split('/Login/LoginGetQRx')[0]
            api_url = f"{base_part}/api/Login/LoginGetQRx"
        
        logger.info(f"调用login_get_qr_x API: {api_url}")
        logger.info(f"请求参数: {body}")
        
        try:
            response = requests.post(
                api_url,
                json=body,
                timeout=15  # 增加超时时间
            )
            
            # 记录响应状态和内容
            logger.info(f"API响应状态码: {response.status_code}")
            logger.info(f"API响应头: {response.headers}")
            
            # 检查响应是否为JSON
            content_type = response.headers.get('Content-Type', '')
            if 'application/json' not in content_type.lower():
                logger.warning(f"API返回的不是JSON格式，而是: {content_type}")
                logger.warning(f"响应内容: {response.text[:200]}...")  # 只记录前200个字符
                
                # 尝试强制解析JSON
                try:
                    return response.json()
                except Exception as json_error:
                    logger.error(f"强制解析JSON失败: {json_error}")
                    # 构造一个错误响应
                    return {
                        "Success": False,
                        "Code": -1,
                        "Message": f"API返回非JSON格式: {response.text[:100]}...",
                        "Data": None
                    }
            
            # 正常返回JSON
            return response.json()
            
        except requests.RequestException as req_error:
            logger.error(f"请求异常: {req_error}")
            # 构造一个错误响应
            return {
                "Success": False,
                "Code": -1,
                "Message": f"请求异常: {req_error}",
                "Data": None
            }
        except Exception as e:
            logger.error(f"未知异常: {e}")
            # 构造一个错误响应
            return {
                "Success": False,
                "Code": -1,
                "Message": f"未知异常: {e}",
                "Data": None
            }

    def login_check_qr(self, uuid: str):
        """检测二维码状态"""
        params = {"uuid": uuid}
        
        # 构造API URL，确保包含/api路径
        api_url = f"{self.base_url}/Login/LoginCheckQR"
        if '/api/' not in api_url and not api_url.endswith('/api'):
            base_part = api_url.split('/Login/LoginCheckQR')[0]
            api_url = f"{base_part}/api/Login/LoginCheckQR"
            
        return requests.post(
            api_url,
            params=params
        ).json()



